import java.util.*;

/**
 * @Author 12629
 * @Description：
 */
public class BinaryTree {

    static class TreeNode {
        public char val;
        //存储左孩子节点的引用
        public TreeNode left;
        //存储右孩子节点的引用
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //不会越界 除非你给的前序遍历 不合理合法
    public static int i = 0;
    /**
     *
     * @param str 一定是合法 合理  的前序遍历的字符串
     * @return
     */
    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if(str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        return root;
    }


    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;

        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    public void preOrderNor(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        ArrayDeque<Integer> s = new ArrayDeque<>();
        s.push(1);
        TreeNode cur = root;
        TreeNode top = null;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val+" ");
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
        System.out.println();
    }

    // 中序遍历
    public void inOrder(TreeNode root){
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }


    public void inOrderNor(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            System.out.print(top.val+" ");
            cur = top.right;
        }
        System.out.println();
    }

    // 后序遍历
    public void postOrder(TreeNode root){
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }


    public void postOrderNor(TreeNode root) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val+" ");
                prev = top;
            }else {
                cur = top.right;
            }
        }
        System.out.println();
    }



    public int countNode = 0;

    /**
     * 求节点个数 遍历思路
     * @param root
     */
    public void nodeSize(TreeNode root) {
        if(root == null) {
            return;
        }
        countNode++;
        nodeSize(root.left);
        nodeSize(root.right);
    }

    /**
     * 求节点个数 子问题思路
     * @param root
     * @return
     */
    public int nodeSize2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int tmp = nodeSize2(root.left) + nodeSize2(root.right) + 1;
        return tmp;
    }

    /**
     * 求叶子节点个数
     * 子问题：左树的叶子 + 右树的叶子  = 整棵树的叶子节点   递推公式
     * 什么是叶子：既没有左子树 又 没有右子树 此时这个节点叫做叶子节点
     * @param root
     * @return
     */
    public int getLeafNodeCount(TreeNode root) {
        if(root == null) {
            return 0;
        }else if(root.left == null && root.right == null) {
            return 1;
        }else {
            return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
        }
    }

    public int leafNodeSize;

    /**
     * 遍历思路 求叶子节点个数
     * @param root
     */
    public void getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafNodeSize++;
        }
        getLeafNodeCount2(root.left);
        getLeafNodeCount2(root.right);
    }

    /**
     * 第K层节点的个数
     * @param root
     * @param k
     * @return
     */
    public int getKLeveNodeSize(TreeNode root,int k) {
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLeveNodeSize(root.left,k-1) +
                getKLeveNodeSize(root.right,k-1);
    }

    /**
     * 求二叉树的高度
     * 时间复杂度：O(n)
     * 空间复杂度：O(logN)
     * @param root
     * @return
     */
    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return getHeight(root.left) > getHeight(root.right) ?
                getHeight(root.left)+1 : getHeight(root.right)+1;
    }


    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);
        return leftH > rightH ? leftH+1 : rightH+1;
    }


    public int maxDepth2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = maxDepth2(root.left);
        int rightH = maxDepth2(root.right);
        return Math.max(leftH,rightH)+1;
    }

    /**
     * 在root这棵树当中 找到val值
     * 时间复杂度：O(n)
     * @param root
     * @param val
     * @return
     */
    public TreeNode find(TreeNode root, char val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode leftValue = find(root.left,val);
        if(leftValue != null) {
            return leftValue;
        }
        TreeNode rightValue = find(root.right,val);
        if(rightValue != null) {
            return rightValue;
        }
        return null;
    }

    /**
     * 时间复杂度：O(min(m,n))
     * @param p m
     * @param q n
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if((p == null && q != null) || (p != null && q == null)) {
            return false;
        }
        //上述if没有生效 代表什么？要么两个都是空 要么两个都不为空
        if(p == null && q == null) {
            return true;
        }
        //走完第2个if 那么p 和 q 都不为空了
        if(p.val != q.val) {
            return false;
        }
        //上述if执行完毕之后，p != null && q != null && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    /**
     * 时间复杂度O(m*n)
     * @param root m
     * @param subRoot n
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) {
            return false;
        }
        if(isSameTree(root,subRoot)) {
            return true;
        }
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    /**
     * 翻转二叉树
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        if(root.left == null && root.right == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }

    /**
     * 判断是否是平衡二叉树
     * 时间复杂度：O(N^2)
     * 字节跳动
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);

        return Math.abs(leftHeight-rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }


    /**
     * 判断二叉树是不是平衡的
     * 时间复杂度：O(N)
     * @param root
     * @return
     */
    public boolean isBalanced2(TreeNode root) {
        if(root == null) {
            return true;
        }
        return maxDepth3(root) >= 0;
    }

    public int maxDepth3(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = maxDepth3(root.left);
        if(leftH == -1) {
            return -1;
        }
        int rightH = maxDepth3(root.right);
        if(leftH >= 0 && rightH >= 0
                && Math.abs(leftH - rightH) <= 1) {
            return Math.max(leftH,rightH)+1;
        }else {
            //证明  高度差是>=2  不平衡的
            return -1;
        }
    }

    /**
     * 判断当前树 是不是镜像对称的
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if(leftTree == null && rightTree != null
                || leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null ) {
            return true;
        }
        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left) ;
    }

    /**
     * 层序遍历
     * @param root
     */
    public void levelOrder(TreeNode root) {
        if(root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
        System.out.println();
    }

    public List<List<Character>> levelOrder2(TreeNode root) {

        List<List<Character>> ret = new ArrayList<>();
        if(root == null) return ret;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            //一层的数据
            List<Character> curList = new ArrayList<>();
            int size = queue.size();//1
            while (size != 0) {
                TreeNode cur = queue.poll();
                //System.out.print(cur.val+" ");
                curList.add(cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(curList);
        }
        return ret;
    }

    /**
     * 给你一棵二叉树 判断这棵树 是不是完全二叉树
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }

        //再次判断队列 是不是里面都是null
        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if(cur == null) {
                queue.poll();
            }else {
                return false;
            }
        }
        return true;
    }

    /**
     * 最近公共祖先
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        if(root == p || root == q) {
            return root;
        }
        TreeNode leftT = lowestCommonAncestor(root.left,p,q);
        TreeNode rightT = lowestCommonAncestor(root.right,p,q);
        if(leftT != null && rightT != null) {
            return root;
        }else if(leftT != null){
            return leftT;
        }else if(rightT != null) {
            return rightT;
        }
        return null;
    }

    /**
     * 找到root到指定节点node路径上的所有节点，存储到stack当中
     * @param root
     * @param node
     * @param stack
     */
    public boolean getPath(TreeNode root,
                           TreeNode node,
                           Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flg = getPath(root.left,node,stack);
        if(flg) {
            return true;
        }
        flg = getPath(root.right,node,stack);
        if(flg) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,p,stack1);
        getPath(root,q,stack2);
        //上述代码已经能够求到 root到指定节点路径上的所有节点
        int size1 = stack1.size();
        int size2 = stack2.size();
        int size = size1 - size2;
        if(size < 0) {
            size = Math.abs(size);
            while (size != 0) {
                stack2.pop();
                size--;
            }
        }else {
            while (size != 0) {
                stack1.pop();
                size--;
            }
        }
        //两个栈的大小是一样的了
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            if(stack1.peek() == stack2.peek()) {
                return stack1.pop();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;
    }

/*

    根据前序遍历 和 中序遍历创建二叉树
    public int preIndex = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {

        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);

        preIndex++;

        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);

        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);

        return root;
    }

    private int findIndex(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }*/


    /*

    根据后序遍历 和 中序遍历创建二叉树

    public int postIndex = 0;

    public TreeNode buildTree(int[] inorder,int[] postorder) {

        postIndex = postorder.length-1;

        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] postorder, int[] inorder,int inbegin,int inend) {

        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);

        postIndex--;

        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);

        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);

        return root;
    }

    private int findIndex(int[] inorder,int inbegin,int inend,int key) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }


     */


    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();

        tree2strChild(root,stringBuilder);

        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode root,StringBuilder stringBuilder) {
        if(root == null) {
            return;
        }
        stringBuilder.append(root.val);
        //判断根的左子树 root == 1, root == 4,  root == 2
        if(root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if(root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        //判断根的右子树
        if(root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}


















